package com.yungu.swift.system.sys.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.miemiedev.mybatis.paginator.domain.Order;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.base.mapper.IMapper;
import com.yungu.swift.base.model.PageVo;
import com.yungu.swift.base.service.impl.BaseServiceImpl;
import com.yungu.swift.lbs.model.param.FenceParam;
import com.yungu.swift.lbs.model.vo.FenceVo;
import com.yungu.swift.lbs.service.FenceService;
import com.yungu.swift.system.sys.dao.SysAreaMapper;
import com.yungu.swift.system.sys.dao.SysFenceMapper;
import com.yungu.swift.system.sys.model.dto.SysAreaDto;
import com.yungu.swift.system.sys.model.dto.SysFenceDto;
import com.yungu.swift.system.sys.model.param.AdminFenceParam;
import com.yungu.swift.system.sys.model.vo.SysFenceVo;
import com.yungu.swift.system.sys.service.SysFenceService;
import com.yungu.swift.utils.MapUtils;
import com.yungu.swift.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SysFenceServiceImpl extends BaseServiceImpl<SysFenceDto> implements SysFenceService {

    @Autowired
    private SysFenceMapper sysFenceMapper;
    @Autowired
    private SysAreaMapper sysAreaMapper;
    @Reference
    private FenceService fenceService;

    @Override
    protected IMapper<SysFenceDto> getMapper() {
        return sysFenceMapper;
    }

    @Override
    public ResponseData<Boolean> addFence(AdminFenceParam adminFenceParam) {
        //新增高德围栏信息
        FenceParam fenceParam = new FenceParam();
        BeanUtils.copyProperties(adminFenceParam, fenceParam);
        ResponseData<String> responseData = fenceService.addFence(fenceParam);
        if (!responseData.isSuccess() || StringUtils.isEmpty(responseData.getData())) {
            return ResponseData.buildErrorResponse(responseData.getErrCode(), responseData.getMsg());
        }
        //新增本地围栏信息
        String gid = responseData.getData();
        SysFenceDto sysFenceDto = new SysFenceDto();
        BeanUtils.copyProperties(adminFenceParam, sysFenceDto);
        sysFenceDto.setFenceGid(gid);
        sysFenceDto.setCreateBy(adminFenceParam.getUserUuid());
        sysFenceDto.setCreateOn(new Date());
        sysFenceDto.setUuid(StringUtils.buildUUID());
        int result = sysFenceMapper.add(sysFenceDto);
        //本地新增失败则删除围栏
        if (result == 0) {
            fenceService.deleteFence(gid);
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "新增失败");
        }
        return ResponseData.buildSuccessResponse(true);
    }

    /**
     * 编辑围栏信息
     *
     * @param sysFenceDto
     * @return
     */
    @Override
    public ResponseData<Boolean> edit(SysFenceDto sysFenceDto) {
        FenceParam fenceParam = new FenceParam();
        BeanUtils.copyProperties(sysFenceDto, fenceParam);
        ResponseData<Boolean> responseData = fenceService.updateFence(fenceParam);
        if (!responseData.isSuccess() || responseData.getData() == null || Objects.equals(responseData.getData(), false)) {
            return ResponseData.buildErrorResponse(responseData.getErrCode(), responseData.getMsg());
        }
        sysFenceDto.setUpdateOn(new Date());
        return ResponseData.buildSuccessResponse(sysFenceMapper.edit(sysFenceDto) > 0);
    }

    /**
     * 删除围栏
     *
     * @param sysFenceDto
     * @return
     */
    @Override
    public ResponseData<Boolean> del(SysFenceDto sysFenceDto) {
        //删除高德围栏信息
        ResponseData<Boolean> responseData = fenceService.deleteFence(sysFenceDto.getFenceGid());
        if (!responseData.isSuccess() || responseData.getData() == null || Objects.equals(responseData.getData(), false)) {
            return ResponseData.buildErrorResponse(responseData.getErrCode(), responseData.getMsg());
        }
        return ResponseData.buildSuccessResponse(sysFenceMapper.del(sysFenceDto) > 0);
    }

    @Override
    public ResponseData<Map<String, Object>> statusFence(double lng, double lat, String diu) {
        ResponseData<List<FenceVo>> responseData = fenceService.statusFence(lng, lat, diu);
        if (responseData.isSuccess() && CollectionUtils.isNotEmpty(responseData.getData())) {
            FenceVo fenceVo = responseData.getData().get(0);
            return ResponseData.buildSuccessResponse(MapUtils.convertObjToMap(fenceVo));
        }
        return ResponseData.buildSuccessResponse(MapUtils.build(2));
    }

    @Override
    public ResponseData<List<SysAreaDto>> findFenceArea(String uuid) {
        List<SysAreaDto> sysAreaDtoList = sysAreaMapper.findFenceArea(MapUtils.build("uuid", uuid));
        return ResponseData.buildSuccessResponse(sysAreaDtoList);
    }

    /**
     * 查询围栏分页信息
     */
    @Override
    public ResponseData<PageVo<SysFenceVo>> queryPageVo(AdminFenceParam adminFenceParam) {
        PageBounds pageBounds = new PageBounds(adminFenceParam.getPageNum(), adminFenceParam.getPageSize());
        if (StringUtils.isNotEmpty(adminFenceParam.getSortString())) {
            pageBounds.setOrders(Order.formString(adminFenceParam.getSortString()));
        }
        PageList<SysFenceVo> pageList = sysFenceMapper.queryPageVo(MapUtils.convertObjToMap(adminFenceParam), pageBounds);
        PageVo<SysFenceVo> pageVo = new PageVo(adminFenceParam.getPageNum(), adminFenceParam.getPageSize(),
                pageList.getPaginator().getTotalCount());
        pageVo.setItems(pageList);
        return ResponseData.buildSuccessResponse(pageVo);
    }

    /**
     * 校验地址是否在围栏中
     */
    @Override
    public ResponseData<Boolean> checkInFence(String cityUuid, Double lng, Double lat, Integer fencePurpose) {
        //diu存在获取不到的问题 暂时固定
        ResponseData<List<FenceVo>> statusRsd = fenceService.statusFence(lng, lat, "861144047871995");
        List<String> fenceGidList = new ArrayList<>();
        if (statusRsd.isSuccess() && CollectionUtils.isNotEmpty(statusRsd.getData())) {
            List<String> collect = statusRsd.getData().stream().filter(fenceVo -> "in".equals(fenceVo.getStatus())).map(fenceVo ->
                    fenceVo.getFenceGid()).collect(Collectors.toList());
            fenceGidList.addAll(collect);
        }
        if(CollectionUtils.isNotEmpty(fenceGidList)){
            //通过城市ID/围栏ID获取围栏信息
            Map<String, Object> paramMap = new HashMap<>(4);
            paramMap.put("fenceGidList", fenceGidList);
            paramMap.put("cityUuid", cityUuid);
            paramMap.put("fencePurpose", fencePurpose);
            List<SysFenceDto> fenceList = sysFenceMapper.list(paramMap);
            if (CollectionUtils.isNotEmpty(fenceList)) {
                return ResponseData.buildSuccessResponse("坐标在围栏中", true);
            }
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "坐标不在围栏中");
    }

}
